package com.woniuxy.dr_mall.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.woniuxy.dr_mall.entity.*;
import com.woniuxy.dr_mall.global.Global;
import com.woniuxy.dr_mall.global.ResponseStateCode;
import com.woniuxy.dr_mall.service.IDrPictureService;
import com.woniuxy.dr_mall.service.IDrProductsService;
import com.woniuxy.dr_mall.service.IDrSpecPriceService;
import com.woniuxy.dr_mall.service.IDrUserFavoriteService;
import com.woniuxy.dr_mall.utils.SpecUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 张哲轩
 * @since 2021-08-11
 */
@RestController
@Slf4j
@RequestMapping("/dr_mall/drProducts")
public class DrProductsController {
    @Autowired
    private IDrProductsService drProductsService;

    @Autowired
    private IDrPictureService pictureService;

    @Autowired
    private IDrUserFavoriteService userFavoriteService;

    @Autowired
    private IDrSpecPriceService specPriceService;

    @Value("${dr.images}")
    private String imagePath;

    /**
     * 根据商品id查询具体信息
     *
     * @param id 主键
     * @return 商品信息
     * @author yy
     */
    @GetMapping("getProduct/{id}")
    public MyResponseEntity<DrProducts> getProduct(@PathVariable int id) {
        log.debug("id:{}", id);
        return new MyResponseEntity<>(drProductsService.getProductById(id));
    }

    /**
     * @Description:
     * @Param: []
     * @return: com.woniuxy.dr_mall.entity.MyResponseEntity
     * @Author: 杨耀
     * @Date: 2021/8/18
     * @Time: 12:02
     */
    @GetMapping("collect/{pid}")
    public MyResponseEntity collect(HttpSession session, @PathVariable Integer pid) {
        DrUser user = (DrUser) session.getAttribute("user");
        QueryWrapper<DrUserFavorite> queryWrapper = new QueryWrapper();
        queryWrapper.eq("userid", user.getId());
        queryWrapper.eq("productid", pid);
        DrUserFavorite userFavorite = userFavoriteService.getOne(queryWrapper);
        log.debug("userFavorite:{}", userFavorite);
        if (userFavorite == null) {
            userFavoriteService.add(user.getId(), pid);
            return new MyResponseEntity(userFavorite);
        } else {
            userFavoriteService.deleteFavorite(userFavorite.getUserId(), userFavorite.getProductId());
            return new MyResponseEntity(userFavorite);
        }

    }

    @GetMapping("viewProducts")
    @ResponseBody
    public MyResponseEntity<List<DrProducts>> viewProducts(String popular, String favor, String hot) {
        List<DrProducts> products = new ArrayList<>();
        if (popular != null) {
            products = drProductsService.getByPopular(popular);
        } else if (favor != null) {
            products = drProductsService.getByFavor(favor);
        } else {
            products = drProductsService.getByHot(hot);
        }
        for (DrProducts product : products) {
            product.setMinPrice(drProductsService.getMinPrice(product.getId()));
        }
        log.debug("products:{}", products);
        return new MyResponseEntity<>(products);
    }

    /**
     * @param id:
     * @param file:
     * @return com.woniuxy.dr_mall.entity.MyResponseEntity<?>
     * @description:
     * @Author 张哲轩
     * @Date 2021/8/19 0:12
     */
    @PostMapping("add_product_pic")
    public MyResponseEntity<?> addProductPic(Integer id, @RequestBody MultipartFile[] file) throws IOException {
        DrProducts product = new DrProducts();
        boolean defaultFlag = true;
        for (MultipartFile subFile : file) {
            String originName = subFile.getOriginalFilename();
            String suffix = originName.substring(originName.lastIndexOf("."));
            String fileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
            subFile.transferTo(new File(imagePath + "\\" + fileName));
            DrPicture picture = new DrPicture();
            picture.setProductId(id);
            picture.setImage(fileName);
            //设置第一张为默认图片
            if (defaultFlag) {
                picture.setIsDefault(Global.NORMAL);
                defaultFlag = false;
            } else {
                picture.setIsDefault(Global.UNNORMAL);
            }
            pictureService.save(picture);
        }
        return MyResponseEntity.SUCCESS;
    }

    /**
     * @param addProduct:
     * @return com.woniuxy.dr_mall.entity.MyResponseEntity<java.lang.Integer>
     * @description:
     * @Author 张哲轩
     * @Date 2021/8/19 0:12
     */
    @PostMapping("add_product")
    public MyResponseEntity<?> addProduct(@RequestBody AddProduct addProduct) {
        String productName=addProduct.getName();
        QueryWrapper<DrProducts> wrapper = new QueryWrapper<>();
        wrapper.eq("name",productName);
        DrProducts oldProduct =  drProductsService.getOne(wrapper);
        if(oldProduct!=null){
            //商品已存在
            return new MyResponseEntity<>(ResponseStateCode.PRODUCT_DUPLICATE,"商品重复");
        }
        //给商品表添加信息
        DrProducts product = new DrProducts();
        product.setProductNo(addProduct.getProductNo());
        product.setName(addProduct.getName());
        product.setFavor(addProduct.getFavor());
        product.setHot(addProduct.getHot());
        product.setPopular(addProduct.getPopular());
        product.setCategoryId(addProduct.getCategoryId());
        product.setStatus(Global.NORMAL);
        drProductsService.add(product);
        int productId=product.getId();
        log.debug("id:{}", productId);
        //给sku表添加信息
        DrSpecPrice specPrice = new DrSpecPrice();
        specPrice.setProductId(productId);
        SpecUtil.addSkuSpecs(addProduct, specPrice);
        specPrice.setPrice(addProduct.getPrice());
        specPrice.setStock(addProduct.getStock());
        specPriceService.save(specPrice);
        return new MyResponseEntity<Integer>(productId);
    }

    @GetMapping("down_product/{id}")
    public MyResponseEntity<?> downProduct(@PathVariable("id") Integer id){
        DrProducts product =new DrProducts();
        product.setId(id);
        product.setStatus(Global.UNNORMAL);
        drProductsService.updateById(product);
        return MyResponseEntity.SUCCESS;
    }

    @GetMapping("up_product/{id}")
    public MyResponseEntity<?> upProduct(@PathVariable("id") Integer id){
        DrProducts product =new DrProducts();
        product.setId(id);
        product.setStatus(Global.NORMAL);
        drProductsService.updateById(product);
        return MyResponseEntity.SUCCESS;
    }
}

